package com.zhenti.z1;

public class zhenti_P3 {
    public static void main(String[] args) {
        int arr[] = {2,2,1,2};
        System.out.println(minCandy(arr));
    }
    public static int minCandy(int arr[]){
        if (arr == null || arr.length == 0)
            return 0;
        if (arr.length == 1)
            return 1;
        int n = arr.length;
        int minIndex = 0;
        for (int i = 0; i < n; i++) {
            if (arr[i] <= nextIndex(i,n) && arr[i] <= leftIndex(i,n)){
                minIndex = i;
                break;
            }
        }
        int nums[] = new int[n+1];
        for (int i = 0; i <= n; i++,minIndex = nextIndex(minIndex,n)) {
            nums[i] = arr[minIndex];
        }
        int left[] = new int[n+1];
        left[0] = 1;
        for (int i = 1; i <= n ; i++) {
            left[i] = nums[i] > nums[i-1] ? (left[i-1] +1) : 1;
        }

        int right[] = new int[n+1];
        right[n] = 1;
        for (int i = n-1; i >= 0; i--) {
            right[i] = nums[i] >nums[i+1] ? (right[i+1] +1) : 1;
        }
        int ans = 0;
        for (int i = 0; i < n; i++) {
            ans += Math.max(left[i],right[i]);
        }
        return ans;

    }
    public static int nextIndex(int i, int n){
        return i == n-1 ? 0 : (i+1);
    }
    public static int leftIndex(int i, int n){
        return i == 0 ? (n-1) : (i+1);
    }
}
